package com.zensun.system.service.impl;

import com.zensun.common.constant.Constants;
import com.zensun.common.core.redis.RedisCache;
import com.zensun.system.domain.SysArea;
import com.zensun.system.domain.TreeSelect;
import com.zensun.system.mapper.SysAreaMapper;
import com.zensun.system.service.ISysAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 省市县 服务层处理
 *
 * @author gmk
 */
@Service
public class SysAreaServiceImpl implements ISysAreaService {
    @Resource
    RedisCache redisCache;
    @Autowired
    private SysAreaMapper areaMapper;

    @Override
    public List<SysArea> selectAreaList() {
        List<SysArea> areaCacheList = redisCache.getCacheList(Constants.AREA_KEY);
        if (CollectionUtils.isEmpty(areaCacheList)) {
            List<SysArea> areas = areaMapper.selectAreaList();
            redisCache.setCacheList(Constants.AREA_KEY, areas);
        }
        return redisCache.getCacheList(Constants.AREA_KEY);

    }

    @Override
    public List<TreeSelect> buildAreaTreeSelect(List<SysArea> areas) {
        List<SysArea> areaTrees = buildAreaTree(areas);
        return areaTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    private List<SysArea> buildAreaTree(List<SysArea> areas) {
        List<SysArea> areaList = areas.stream().filter((area) -> {
            //查询一级数据
            return area.getAreaParentCode().equals("0");
        }).map((area) -> {
            //构造一级数据的children
            area.setChildren(getChildrens(area, areas));
            return area;
        }).collect(Collectors.toList());
        return areaList;
    }

    public List<SysArea> getChildrens(SysArea root, List<SysArea> areaList) {
        List<SysArea> collect = areaList.stream().filter((area) -> {
            return area.getAreaParentCode().equals(root.getAreaCode());
        }).map((area) -> {
            area.setChildren(getChildrens(area, areaList));
            return area;
        }).collect(Collectors.toList());

        return collect;
    }
}
